const defaultOptions = {
    parEl: document.body, // 父元素（不动的大盒子）
    tarEl: "app", // 目标元素（滑动的子盒子）
    pullCallback: () => {
      // 有效下拉回调，通常在内部获取数据并调用 finish() 方法
      window.location.reload();
    },
  };
  const parseTime = (time_Date = new Date()) => {
    const h = time_Date.getHours();
    const s = time_Date.getMinutes();
    const ss = time_Date.getSeconds();
    const format = (t) => (t > 9 ? t : "0" + t);
    return format(h) + ":" + format(s) + ":" + format(ss);
  };
  function pullDownRefresh(_option) {
    const box_height = 100;
    const options = {
      ...defaultOptions,
      ..._option,
    };
    const ifQQBrowse = () => {
      // qq系浏览器
      const ua = navigator.userAgent.toLowerCase();
      return !!ua.match(/mqqbrowser|qzone|qqbrowser/i);
    };
    let { parEl, tarEl, pullCallback } = options;
    if (typeof parEl === "string") {
      parEl = document.getElementById(parEl);
    }
    if (typeof tarEl === "string") {
      tarEl = document.getElementById(tarEl);
    }
    const parentToDistance = parEl.getBoundingClientRect().top; //父元素距离顶部距离
    console.log("父元素距离顶部距离", parentToDistance);
    const tarElCache = { ...tarEl.style }; //记录初始的元素样式，用于后续恢复
    if (!tarElCache.position) {
      tarEl.style["position"] = "relative";
      tarElCache.position = "relative";
    }

    const pullTextEl = document.createElement("div"); //刷新盒子
    const pullLoadingEl = document.createElement("div"); //加载圆圈
    const pulltext_span = document.createElement("div"); //加载圆圈

    pullTextEl.style = `width: 100%; 
    text-align: center; 
    position: absolute; 
    height:${box_height}px;
    left: 0; 
    top: -${box_height}px; 
    font-size:16px;
    display: none;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    `;
    pullTextEl.innerText = "";

    pullLoadingEl.style = `
    display:none;
     width: 25px;
    height: 25px;
    border: 3px solid #ddd;
    border-radius: 50%;
    border-bottom: 3px solid #717171;
    transform: rotate(0deg);
    animation: loading 1s linear infinite;
    `;
    let last_Date = new Date();
    const init = () => {
      let TAR_MAX_LENS = 100; //定义最大拖动是100
      let refreshStatus = false; //松开后是否执行刷新动画
      if (ifQQBrowse()) return; //判断qq浏览器
      tarEl.appendChild(pullTextEl); //在下拉元素顶部添加元素
      pullTextEl.appendChild(pullLoadingEl);
      pullTextEl.appendChild(pulltext_span);
      pullTextEl.childNodes[1].innerText = `下拉可以刷新... \n最后更新：${parseTime(
        last_Date
      )}`;
      console.log(pullTextEl.childNodes[1]);
      let start_Pt, move_Lens; //定义初始相对于页面顶部的坐标，以及后续滑动的距离
      const canTarElHandler = (moveLen) => {
        if (moveLen > TAR_MAX_LENS) moveLen = TAR_MAX_LENS;
        const tarElToInstance = tarEl.getBoundingClientRect().top; //下拉元素相对于视口顶部距离
        const tarElToParentLens = tarElToInstance - parentToDistance; //判断是否是正确的下拉，根据下拉元素的顶部和父元素顶部进行计算
        if (tarElToParentLens >= 0) {
          //正确下拉
          pullTextEl.style["display"] = "flex";
        }
        if (moveLen > 0 && moveLen < 50) {
          const _movelen = ((box_height - moveLen) / box_height) * moveLen;
          tarEl.style["transform"] = `translate(0,${_movelen}px)`;
          // }else if(moveLen>=50&&moveLen<100){
        } else {
          tarEl.style["transform"] = `translate(0,${moveLen}px)`;
        }

        // 下拉触发
        if (tarElToParentLens < 75) {
          pullTextEl.childNodes[1].innerText = `下拉可以刷新... \n最后更新：${parseTime(
            last_Date
          )}`;
          refreshStatus = false;
        } else {
          pullTextEl.childNodes[1].innerText = `松开立即刷新... \n最后更新：${parseTime(
            last_Date
          )}`;
          refreshStatus = true;
        }
      };
      tarEl.addEventListener("touchstart", (e) => {
        console.log(e.touches[0]);
        start_Pt = e.touches[0].pageY; //触摸点相对于HTML顶部边缘的坐标 https://developer.mozilla.org/zh-CN/docs/Web/API/Touch
        tarEl.style["transition"] = "transform 0s";
      });
      tarEl.addEventListener("touchmove", (e) => {
        move_Lens = e.touches[0].pageY - start_Pt;
        canTarElHandler(move_Lens);
      });
      tarEl.addEventListener("touchend", () => {
        const tarElToInstance = tarEl.getBoundingClientRect().top; //下拉元素相对于视口顶部距离
        const tarElToParentLens = tarElToInstance - parentToDistance; //下拉元素距离 父级的顶部 的距离
        if (tarElToParentLens > 0) {
          if (refreshStatus) {
            pullLoadingEl.style["display"] = "block";
            pullTextEl.childNodes[1].innerText = `正在刷新... \n最后更新：${parseTime(
              last_Date
            )}`;
            pullCallback && pullCallback();
            tarEl.style["transition"] = "transform 0.4s";
            tarEl.style["transform"] = `translate(0,${box_height}px)`;
          } else {
            tarEl.style["transition"] = "transform 0.4s";
            tarEl.style["transform"] = `translate(0,${0}px)`;
            setTimeout(() => {
              pullTextEl.style["display"] = "none";
              tarEl.style = tarElCache;
            }, 400);
          }
        } else {
          pullTextEl.style["display"] = "none";
        }
      });
    };
    const finish = () => {
      pullTextEl.childNodes[1].innerText = `刷新成功... \n最后更新：${parseTime()}`;
      last_Date = new Date();
      setTimeout(() => {
        tarEl.style["transition"] = "transform 0.2s";
        tarEl.style["transform"] = "translate(0,0)";
        setTimeout(() => {
          pullTextEl.style["display"] = "none";
        }, 400);
      }, 500);
    };
    return {
      init,
      finish,
    };
  }

  function yourHandler() {
    return new Promise((res, rej) => {
      setTimeout(() => {
        res("下拉刷新成功");
      }, 5000);
    });
  }
  const pullInstances = pullDownRefresh({
    parEl: "page-9527", // 作用元素父元素
    tarEl: "pullTarEl", // 目标作用元素
    pullCallback: async () => {
      // 产生有效下拉后释放触发回调方法
      await yourHandler();
      pullInstances.finish();
    },
  });
  pullInstances.init();